package run.bottle.mail.handle;

import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import run.bottle.mail.model.entity.BaseResponse;
import run.bottle.mail.model.entity.Email;
import run.bottle.mail.model.enums.EmailType;

/**
 * 描述
 *
 * @author LiYuanCheng
 * @date 2020-06-05 14:31
 */
@Component
public class HtmlEmailHandler implements EmailHandler {

  private static final Logger logger = LoggerFactory.getLogger(HtmlEmailHandler.class);

  public static final String SF_FILE_SEPARATOR = System.getProperty("file.separator");

  @Autowired
  private JavaMailSender mailSender;

  /**
   * 发送人
   */
  @Value("${spring.mail.username}")
  public String userName;

  @Override
  public BaseResponse send(Email mail) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper;
    try {
      helper = new MimeMessageHelper(message, true);
      //这里可以自定义发信名称比如：爪哇笔记
      helper.setFrom(userName,"爪哇笔记");
      helper.setTo(mail.getEmail());
      helper.setSubject(mail.getSubject());
      helper.setText(
          "<html><body><img src=\"cid:springcloud\" ></body></html>",
          true);
      // 发送图片
      File file = ResourceUtils.getFile("classpath:static"
          + SF_FILE_SEPARATOR + "image"
          + SF_FILE_SEPARATOR + "springcloud.png");
      helper.addInline("springcloud", file);
      // 发送附件
      file = ResourceUtils.getFile("classpath:static"
          + SF_FILE_SEPARATOR + "file"
          + SF_FILE_SEPARATOR + "bottle.zip");
      helper.addAttachment("Little Bottle", file);
      mailSender.send(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return BaseResponse.ok("发送成功！");
  }

  @Override
  public EmailType getEmailType() {
    return EmailType.HTML;
  }
}
